/**  
 * @Title: DatasourceJdbcService.java
 * @Description: TODO(描述)
 * @author liuyi
 * @date 2023-04-27 09:01:49 
 */  
package com.fsxgt.datagrid.ds.service.impl;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fsxgt.datagrid.ds.bo.DatasourceJdbcBO;
import com.fsxgt.datagrid.ds.component.QueryComponent;
import com.fsxgt.datagrid.ds.dao.DatasourceJdbcMapper;
import com.fsxgt.datagrid.ds.exception.DsException;
import com.fsxgt.datagrid.ds.handler.DbHandler;
import com.fsxgt.datagrid.ds.utils.AESUtil;

import lombok.extern.slf4j.Slf4j;


/**  
 * @ClassName: DatasourceJdbcService
 * @Description: TODO(描述)
 * @author liuyi
 * @date 2023-04-27 09:01:49 
*/
@Slf4j
@Service
public class DatasourceJdbcService {
	

	@Autowired
	private QueryComponent queryComponent;	

	@Autowired
	private DatasourceJdbcMapper datasourceJdbcMapper;	

	public void addDatasource(DatasourceJdbcBO datasourceJdbcBO) {
		datasourceJdbcBO.setStatus(1);
		datasourceJdbcBO.setCreateTime(new Date());
		datasourceJdbcBO.setJdbcUsername(AESUtil.encrypt(datasourceJdbcBO.getJdbcUsername()));
		datasourceJdbcBO.setJdbcPassword(AESUtil.encrypt(datasourceJdbcBO.getJdbcPassword()));
		datasourceJdbcMapper.insertDatasource(datasourceJdbcBO);
	}
	
	public void deleteDatasource(DatasourceJdbcBO datasourceJdbcBO) {
		datasourceJdbcMapper.deleteDatasource(datasourceJdbcBO);
		queryComponent.removeCache(datasourceJdbcBO.getId());
	}
	
	
	public void modifyDatasource(DatasourceJdbcBO datasourceJdbcBO) {
		datasourceJdbcBO.setStatus(1);
		String userName = AESUtil.decrypt(datasourceJdbcBO.getJdbcUsername());
        //  判断账密是否为密文
        if (userName == null) {
        	datasourceJdbcBO.setJdbcUsername(AESUtil.encrypt(datasourceJdbcBO.getJdbcUsername()));
        }
        String pwd = AESUtil.decrypt(datasourceJdbcBO.getJdbcPassword());
        if (pwd == null) {
        	datasourceJdbcBO.setJdbcPassword(AESUtil.encrypt(datasourceJdbcBO.getJdbcPassword()));
        }
		datasourceJdbcMapper.updateDatasource(datasourceJdbcBO);
		queryComponent.removeCache(datasourceJdbcBO.getId());
	}

	public List<DatasourceJdbcBO> findDatasource(DatasourceJdbcBO datasourceJdbcBO) {

        return datasourceJdbcMapper.selectDatasource(datasourceJdbcBO);
    }
	
	
	
	public DatasourceJdbcBO getDatasourceById(Long datasourceId) {
		
		DatasourceJdbcBO datasourceJdbcBO = new DatasourceJdbcBO();
		datasourceJdbcBO.setId(Long.valueOf(datasourceId));

        return findDatasource(datasourceJdbcBO).get(0);
    }
	

	
	public void runTest(DatasourceJdbcBO datasourceJdbcBO) throws Exception {


		
		DbHandler dbHandler=queryComponent.getTestHandler(datasourceJdbcBO);
		
		boolean b=dbHandler.runTest();
		
		if(!b) {
			throw new DsException("数据库连接失败");
		}
		
	}
	
	
	
	
	

}
